"""
图片显示组件
负责图片处理、检测和显示
"""

import cv2
import numpy as np
from pathlib import Path

from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QPixmap, QImage


class ImageDisplayWidget(QWidget):
    """
    图片显示组件
    
    功能：
    - 显示图片
    - 处理图片检测
    - 显示检测结果
    """
    
    resultReady = Signal(dict)
    
    def __init__(self):
        super().__init__()
        self.detector = None
        self.recognizer = None
        self.processor = None
        self.init_ui()
        
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        
        # 图片显示标签
        self.image_label = QLabel()
        self.image_label.setMinimumSize(640, 480)
        self.image_label.setStyleSheet(
            "QLabel { background-color: #f0f0f0; border: 2px dashed #ccc; }"
        )
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setText("点击'打开图片'选择要检测的图片")
        layout.addWidget(self.image_label)
        
        # 图片信息显示
        self.image_info_label = QLabel("图片信息: 未加载")
        layout.addWidget(self.image_info_label)
        
    def set_models(self, detector, recognizer, processor):
        """设置检测模型"""
        self.detector = detector
        self.recognizer = recognizer
        self.processor = processor
        
    def process_image(self, image_path):
        """处理单张图片"""
        try:
            # 读取图片
            image = cv2.imread(image_path)
            if image is None:
                raise ValueError("无法读取图片")
            
            # 获取图片信息
            height, width = image.shape[:2]
            file_size = Path(image_path).stat().st_size / 1024  # KB
            
            # 更新图片信息显示
            self.image_info_label.setText(
                f"图片信息: {width}x{height} | {file_size:.1f}KB | {Path(image_path).name}"
            )
            
            # 检测车牌
            detections = self.detector.detect(image)
            
            detection_count = 0
            # 处理每个检测结果
            for detection in detections:
                bbox = detection['bbox']
                
                # 提取车牌区域
                plate_region = self.processor.extract_plate_region(image, bbox)
                
                # 识别车牌
                result = self.recognizer.recognize(plate_region)
                
                # 只处理置信度较高的结果
                if result['confidence'] > 0.3:
                    detection_count += 1
                    
                    # 绘制结果
                    image = self._draw_bbox(
                        image, bbox, 
                        f"{result['text']} ({result['confidence']:.2f})"
                    )
                    
                    # 发送结果信号
                    self.resultReady.emit({
                        'bbox': bbox,
                        'plate_number': result['text'],
                        'confidence': result['confidence'],
                        'timestamp': self._get_timestamp()
                    })
            
            # 更新图片信息，包含检测结果
            self.image_info_label.setText(
                f"图片信息: {width}x{height} | {file_size:.1f}KB | "
                f"{Path(image_path).name} | 检测到 {detection_count} 个车牌"
            )
                
            # 显示结果图像
            self._display_image(image)
            
        except Exception as e:
            self.image_info_label.setText(f"处理失败: {e}")
            raise e
            
    def _display_image(self, image):
        """显示图片到界面"""
        # 转换颜色空间
        rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        
        # 调整大小以适应显示区域
        h, w, ch = rgb_image.shape
        bytes_per_line = ch * w
        
        # 创建QImage
        qt_image = QImage(
            rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888
        )
        
        # 缩放到合适大小
        pixmap = QPixmap.fromImage(qt_image)
        scaled_pixmap = pixmap.scaled(
            self.image_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation
        )
        
        self.image_label.setPixmap(scaled_pixmap)
        
    def _draw_bbox(self, image, bbox, text):
        """绘制检测框"""
        x1, y1, x2, y2 = bbox
        cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
        cv2.putText(image, text, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        return image
        
    def _get_timestamp(self):
        """获取时间戳"""
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S") 